/**
 * Desc：单例模式(Singleton),保证一个类仅有一个实例,并提供一个访问它的全局访问点.
 * Created by VincentZee on 2019/2/21
 */
public class SingletonPatternDemo {
    public static void main(String[] args) {
        // 懒汉式
        /*LazySingleton singleton1 = LazySingleton.getSingleton();
        LazySingleton singleton2 = LazySingleton.getSingleton();*/

        // 懒汉式-双重检验锁
        /*DoubleCheckSingleton singleton1 = DoubleCheckSingleton.getSingleton();
        DoubleCheckSingleton singleton2 = DoubleCheckSingleton.getSingleton();*/

        // 饿汉式
        HungrySingleton singleton1 = HungrySingleton.getSingleton();
        HungrySingleton singleton2 = HungrySingleton.getSingleton();

        System.out.println(singleton1 == singleton2);
    }
}

// 写法-懒汉式(锁方法效率低)
class LazySingleton{
    // 需要时进行实例化(懒汉式)
    public static LazySingleton singleton;
    private LazySingleton(){

    }

    public static synchronized LazySingleton getSingleton(){
        if(null == singleton){
            singleton = new LazySingleton();
        }
        return singleton;
    }
}

// 写法-双重检验锁(效率高)
class DoubleCheckSingleton{
    public static DoubleCheckSingleton singleton;
    private DoubleCheckSingleton(){

    }

    public static DoubleCheckSingleton getSingleton(){
        if(null == singleton){
            synchronized (DoubleCheckSingleton.class){
                if(null == singleton){
                    singleton = new DoubleCheckSingleton();
                }
            }
        }
        return singleton;
    }
}

// 写法-饿汉式
class HungrySingleton{
    private static HungrySingleton singleton = new HungrySingleton();
    private HungrySingleton(){

    }

    public static HungrySingleton getSingleton(){
        return singleton;
    }
}
